/**
 * Copyright (c) 2018 开源 All rights reserved.
 * <p>
 * https://www.chengcang.com
 * <p>
 * 版权所有，侵权必究！
 */

package com.chengcang.api.modules.sys.service.impl;

import com.chengcang.api.modules.login.utils.UserHolder;
import com.chengcang.api.modules.login.vo.TenantVO;
import com.chengcang.api.modules.login.vo.UserVO;
import com.chengcang.api.modules.sys.dao.SysUserTokenDao;
import com.chengcang.api.modules.sys.dto.SysUserDTO;
import com.chengcang.api.modules.sys.entity.SysTenantEntity;
import com.chengcang.api.modules.sys.entity.SysUserTenantEntity;
import com.chengcang.api.modules.sys.entity.SysUserTokenEntity;
import com.chengcang.api.modules.sys.service.SysTenantService;
import com.chengcang.api.modules.sys.service.SysUserService;
import com.chengcang.api.modules.sys.service.SysUserTenantService;
import com.chengcang.api.modules.sys.service.SysUserTokenService;
import com.chengcang.common.constant.Constant;
import com.chengcang.common.constant.TokenExpireConstant;
import com.chengcang.common.redis.RedisUtils;
import com.chengcang.common.service.impl.BaseServiceImpl;
import com.chengcang.common.utils.Result;
import com.chengcang.common.utils.TokenGenerator;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class SysUserTokenServiceImpl extends BaseServiceImpl<SysUserTokenDao, SysUserTokenEntity> implements SysUserTokenService {


    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysTenantService sysTenantService;

    @Autowired
    private SysUserTenantService sysUserTenantService;

    @Override
    public Result createToken(Long userId, Long tenantId) {
        //用户token
        String token;

        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + TokenExpireConstant.EXPIRE * 1000);

        //判断是否生成过token
        SysUserTokenEntity tokenEntity = baseDao.getByUserId(userId);
        if (tokenEntity == null) {
            //生成一个token
            token = TokenGenerator.generateValue();

            tokenEntity = new SysUserTokenEntity();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setUpdateDate(now);
            tokenEntity.setExpireDate(expireTime);
            tokenEntity.setTenantId(tenantId);
            tokenEntity.setDeleted(0);

            //保存token
            this.insert(tokenEntity);
        } else {
            //判断token是否过期
            //允许多端登录
            /*if (tokenEntity.getExpireDate().getTime() < System.currentTimeMillis()) {
                //token过期，重新生成token
                token = TokenGenerator.generateValue();
            } else {
                token = tokenEntity.getToken();
            }*/
            //不允许多端登录
            token = TokenGenerator.generateValue();
            tokenEntity.setToken(token);
            tokenEntity.setUpdateDate(now);
            tokenEntity.setExpireDate(expireTime);
            tokenEntity.setTenantId(tenantId);
            tokenEntity.setDeleted(0);

            //更新token
            this.updateById(tokenEntity);
        }
        SysUserDTO user = sysUserService.get(userId);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        UserHolder.setUser(user);

        List<SysTenantEntity> tenantList = sysTenantService.getListByUserId(userId);

        List<TenantVO> tenantVOS = tenantList.stream().map(e -> {
            TenantVO vo = new TenantVO();
            BeanUtils.copyProperties(e, vo);
            vo.setTenantId(e.getId());
            vo.setLogo(e.getLogo());
            return vo;
        }).collect(Collectors.toList());

        Map<String, Object> map = new HashMap<>(2);
        map.put(Constant.TOKEN_HEADER, token);
        map.put("expire", TokenExpireConstant.EXPIRE);
        map.put("user", userVO);
        map.put("tenants", tenantVOS);
        return new Result().ok(map);
    }

    @Override
    public void logout(Long userId) {
        //清空redis用户信息
        SysUserTokenEntity sysUserTokenEntity = baseDao.getByUserId(userId);
        if (Objects.nonNull(sysUserTokenEntity)) {
            redisUtils.delete(sysUserTokenEntity.getToken());
//			Optional.ofNullable(SecurityUser.getTenantId()).ifPresent(o ->
//					redisUtils.setBit(String.valueOf(SecurityUser.getTenantId()), userId, false)
//			);
        }
        //生成一个token
        String token = TokenGenerator.generateValue();

        //修改token
        baseDao.updateToken(userId, token);
    }

    @Override
    public SysUserTokenEntity getByToken(String token) {
        return baseDao.getByToken(token);
    }
}